package com.sskj.cndragon.ui.activity;


import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.media.audiofx.Visualizer;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.permissions.RxPermissions;
import com.sskj.cndragon.R;
import com.sskj.cndragon.bean.BankInfoBean;
import com.sskj.cndragon.bean.RateBean;
import com.sskj.cndragon.http.HttpConfig;
import com.sskj.cndragon.presenter.RechargeActivityPresenter;
import com.sskj.cndragon.view.SelectPictureDialog;
import com.sskj.cndragon.view.ToolBarLayout;
import com.sskj.common.base.App;
import com.sskj.common.box.inputfilter.MoneyValueFilter;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.ImageUtil;
import com.sskj.common.util.NumberUtil;
import com.sskj.common.util.SPUtil;
import com.sskj.common.util.ToastUtil;
import com.sskj.lib.SPConfig;
import com.sskj.lib.base.BaseActivity;

import java.io.File;
import java.lang.reflect.MalformedParameterizedTypeException;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;


public class RechargeActivity extends BaseActivity<RechargeActivityPresenter> {

    @BindView(R.id.toolbar)
    ToolBarLayout toolbar;
    @BindView(R.id.num_edit)
    EditText numEdit;
    @BindView(R.id.withdraw_edit)
    EditText withdrawEdit;
    @BindView(R.id.img_upload)
    ImageView imgUpload;
    @BindView(R.id.btn_submit)
    Button btnSubmit;
    @BindView(R.id.bank_name)
    TextView bankName;
    @BindView(R.id.bank_branch)
    TextView bankBranch;
    @BindView(R.id.bank_account)
    TextView bankAccount;

    private String exchangeRate;
    private String mImagePath;
    private SelectPictureDialog selectPictureDialog;

    public static void start(Context context) {
        Intent intent = new Intent(context, RechargeActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_recharge;
    }

    @Override
    public RechargeActivityPresenter getPresenter() {
        return new RechargeActivityPresenter();
    }

    @Override
    protected void initView() {
        super.initView();
        toolbar.setLeftButtonOnClickListener(view -> finish());
        ClickUtil.click(300, imgUpload, () -> {
            new RxPermissions(RechargeActivity.this)
                    .request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
                    .subscribe(granted -> {
                        if (granted) {
                            selectPic();
                        }
                    });
        });

        mPresenter.getCrystalRate();

    }

    @Override
    protected void initData() {
        super.initData();
        mPresenter.getBankInfo();
        ClickUtil.click(300, btnSubmit, new ClickUtil.Click() {
            @Override
            public void click() {
                if (isEmpty(getEtext(numEdit))) {
                    ToastUtil.showShort(App.INSTANCE.getString(R.string.appQingshuruchongzhishuliang));
                    return;
                }
                if (isEmpty(getEtext(withdrawEdit))) {
                    ToastUtil.showShort(App.INSTANCE.getString(R.string.appHuoquhuilvxinxishibai));
                    return;
                }
                if (isEmpty(mImagePath)) {
                    ToastUtil.showShort(App.INSTANCE.getString(R.string.appShangchuanzhuanzhangpingzheng));
                    return;
                }
                mPresenter.recharge(SPUtil.get(SPConfig.ID, "")
                        , getEtext(numEdit)
                        , getEtext(withdrawEdit)
                        , mImagePath);
            }
        });

        numEdit.setFilters(new InputFilter[]{new MoneyValueFilter().setDigits(2)});

        numEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                        s = s.toString().subSequence(0,
                                s.toString().indexOf(".") + 3);
                        numEdit.setText(s);
                        numEdit.setSelection(s.length());
                    }
                }

                //如果.在起始位置,则起始位置自动补0
                if (s.toString().trim().substring(0).equals(".")) {
                    s = "0" + s;
                    numEdit.setText(s);
                    numEdit.setSelection(2);
                }

                //如果起始位置为0并且第二位跟的不是".",则无法后续输入
                if (s.toString().startsWith("0")
                        && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        numEdit.setText(s.subSequence(0, 1));
                        numEdit.setSelection(1);
                        return;
                    }
                }

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!TextUtils.isEmpty(s.toString()) && !isEmpty(exchangeRate)) {
                    withdrawEdit.setText(NumberUtil.keepMax2(Double.valueOf(s.toString()) * Double.valueOf(exchangeRate)));
                } else {
                    withdrawEdit.setText("");
                }
            }
        });
    }

    public void selectPic() {
        if (selectPictureDialog == null) {
            selectPictureDialog = new SelectPictureDialog(this);
        }
        selectPictureDialog.setOnSelectListener(new SelectPictureDialog.SelectListener() {
            @Override
            public void selectByAlbum() {
                PictureSelector.create(RechargeActivity.this)
                        .openGallery(PictureMimeType.ofImage())
                        .maxSelectNum(1)
                        .compress(true)
                        .minimumCompressSize(100)
                        .forResult(PictureConfig.CHOOSE_REQUEST);
            }

            @Override
            public void selectByPhoto() {
                PictureSelector.create(RechargeActivity.this)
                        .openCamera(PictureMimeType.ofImage())
                        .maxSelectNum(1)
                        .compress(true)
                        .minimumCompressSize(100)
                        .forResult(PictureConfig.CHOOSE_REQUEST);
            }
        });
        selectPictureDialog.show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 图片、视频、音频选择结果回调
        if (resultCode == RESULT_OK && requestCode == PictureConfig.CHOOSE_REQUEST) {
            List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
            mPresenter.uploadFile(new File(TextUtils.isEmpty(selectList.get(0).getCompressPath()) ? selectList.get(0).getPath() : selectList.get(0).getCompressPath()));
        }
    }

    public void changeHead(String headUrl) {
        if (headUrl == null) {
            return;
        }
        ImageUtil.setImage(HttpConfig.BASE_URL + headUrl, imgUpload);
        mImagePath = headUrl;
    }

    public void getRateOK(RateBean data) {
        if (data == null) {
            return;
        }
        exchangeRate = data.getValue();
    }

    public void getBankInfoOK(BankInfoBean data) {
        if (data == null) {
            return;
        }
        bankName.setText("开户名:  " + data.getName());
        bankAccount.setText("开户账号:  " + data.getBankCardNo());
        bankBranch.setText("开户行:  " + data.getBankCardType() + data.getBankCardOpenBank());
    }
}
